<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/5
 * Time: 14:43
 */

namespace app\admin\controller;
use app\admin\model\AuthGroup;
use app\admin\model\StatusGroup;
use think\Db;
use app\admin\model\AuthRule;
use think\facade\Cache;

class Role extends Admin
{
    public function index()
    {
//        $search_name=input('search_name');
//        $this->assign('search_name',$search_name);
//        $map=array();
//        if($search_name){
//            $map['admin_username']= array('like',"%".$search_name."%");
//        }
//        $admin_list=Db::name('admin')->where($map)->order('admin_id')->paginate(config('paginate.list_rows'),false,['query'=>get_query()]);
//        $page = $admin_list->render();
//        $this->assign('admin_list',$admin_list);
//        $this->assign('page',$page);
        return $this->fetch();
    }

    /**
     * 角色组列表
     * @return mixed
     */
    public function role_group()
    {
        $auth_group=model('auth_group')->select();
        $this->assign('auth_group',$auth_group);
        return $this->fetch();
    }

    /**
     * 添加用户组
     * @return mixed
     */
    public function add_role()
    {
        return $this->fetch();
    }

    /**
     *添加用户组
     */
    public function add_rolerun()
    {
        if(!request()->isAjax()){
            $this->error('提交方式不正确',url('admin/role/role_group'));
        }else{
            $menu = new AuthGroup();
            $data=input('post.');
            $result=$menu->validate('authGroup')->save($data);
            if(false === $result){
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            }else{
                $this->success('用户组添加成功',url('admin/role/role_group'));
            }
        }
    }
    /**
     * 添加用户组
     * @return mixed
     */
    public function edit_role()
    {
        input('id')?$id = input('id'):$this->error('缺少参数');
        $info= Db::name('AuthGroup')->where(['id'=>$id])->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     *更新用户组
     */
    public function edit_rolerun()
    {
        if(!request()->isAjax()){
            $this->error('提交方式不正确',url('admin/role/role_group'));
        }else{
            $menu = new AuthGroup();
            $data=input('post.');
            !empty($data['status'])?:$data['status']=0;
            $result=$menu->allowField(true)->validate(true)->isUpdate(true)->save($data);
            if($result!==false){
                $this->success('用户组修改成功',url('admin/role/role_group'));
            }else{
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            }
        }
    }

    /**
     * 删除用户组
     * @return \think\response\Json
     */
    public function del_role(){
        $id = $this->request->param('id',0);
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        if(AuthGroup::destroy($id)){
            $arr=['status'=>1,'info'=>'删除成功'];
        } else {
            $arr = ['status' => 0, 'info' => '删除失败'];
        }
        return json($arr);
    }

    /**
     *用户组的权限配置
     */
    public function role_group_access()
    {
        $admin_group=Db::name('auth_group')->where(array('id'=>input('id')))->find();
        $data=AuthRule::get_ruels_tree();
        $this->assign('admin_group',$admin_group);
        $this->assign('datab',$data);
//        halt($data);
        return $this->fetch();
    }
    /**
     * 权限配置保存
     */
    public function role_group_runaccess()
    {
        $new_rules = input('new_rules/a');
        $imp_rules = implode(',', $new_rules);
        $data=array(
            'id'=>input('id'),
            'rules'=>$imp_rules,
        );
        $menu = new AuthGroup();
        $result=$menu->allowField(true)->validate("AuthGroup.edit")->isUpdate(true)->save($data);
        if($result!==false){
            Cache::clear();
            $this->success('权限配置成功',url('admin/role/role_group'));
        }else{
            $this->error($menu->getError());
        }
    }

    public function getStateIds()
    {
        $ids = Db::name('state')->select();
        return $ids;
    }

    /**
     * 给状态授权
     * @return mixed
     */
    public function stateDist()
    {
        $auth_id = input('id',0,'int');
        $authgroup = Db::name('auth_group')->where(['id'=>$auth_id])->find();//当前角色
        $statusdata = Db::name('state')->select();//获取所有的状态
        $authcahzia = StatusGroup::where('auth_id',$auth_id)->column('status_id');//获取所有已经授权的状态id
        $this->assign('statedata',$statusdata);
        $this->assign('auth',implode(',',$authcahzia));
        $this->assign('authgroup',$authgroup);
        return $this->fetch();
    }
    /**
     * 将状态添加到角色组,入参auth_id,status_id
     */
    public function addToGroup(){
        $auth_id = $this->request->post('auth_id');
        $status_id = $this->request->post('status_id/a');
        if( empty($auth_id) ){
            $this->error('参数丢失');
        }
        $statusgroup = new StatusGroup();
        if(is_numeric($auth_id)){
            if(!AuthGroup::get(array('id'=>$auth_id))){
                $this->error('角色不存在！');
            }
        }
        if ( $statusgroup->addToGroup($auth_id,$status_id) ){
            Cache::clear('state');
            $this->success('操作成功');
        }else{
            $this->error($statusgroup->getError());
        }
    }


    public function setStates(){
        if($this->request->isPost()){
            $authdata = $this->request->post();
            if( empty($authdata['auth_id']) ){
                $this->error('参数丢失');
            }elseif( is_numeric($authdata['auth_id']) ){
                if(!AuthGroup::get(array('id'=>$authdata['auth_id']))){
                    $this->error('角色不存在！');
                }else{
                    $data['id'] = $authdata['auth_id'];
                    $data['caneditstates'] = implode(',',$authdata['caneditstates']);
                    $data['editstates'] = implode(',',$authdata['editstates']);
                    $data['baomi'] = intval($authdata['baomi']);
                    $data['hidstates'] = implode(',',$authdata['hidstates']);
                    $res = model('auth_group')->allowField(true)->isUpdate()->save($data);
                    if($res){
                        $this->success('操作成功');
                    }else{
                        $this->error(model('auth_group')->getError());
                    }
                }
            }
        }else{
            $auth_id = input('id',0,'int');
            $authgroup = Db::name('auth_group')->where(['id'=>$auth_id])->find();//当前角色
            $statusdata = Db::name('state')->cache(6000)->select();//获取所有的状态
            $this->assign('statedata',$statusdata);
            $this->assign('authgroup',$authgroup);
            return $this->fetch();
        }
    }
}